package org.gwt.grin.rebind;

import java.util.Formatter;

import org.gwt.grin.rebind.input.SERCHandler;

public class SESegment extends AbstractSENode {

	private final SEFeature[] activeFeatures;
	private final SEFeature[] setupFeatures;
	private final SECommand[] onEntryCommands;
	private final boolean nextOnSetupDone;
	private final SECommand[] nextCommands;
	private final SERCHandler[] rcHandlers;

	public SESegment(String name, SEFeature[] activeFeatures,
			SEFeature[] setupFeatures, SERCHandler[] rcHandlers,
			SECommand[] onEntryCommands, boolean nextOnSetupDone,
			SECommand[] nextCommands) {
		super(name);
		this.activeFeatures = activeFeatures;
		this.setupFeatures = setupFeatures;
		this.rcHandlers = rcHandlers;
		this.onEntryCommands = onEntryCommands;
		this.nextOnSetupDone = nextOnSetupDone;
		this.nextCommands = nextCommands;
	}

	@Override
	public String write(ShowBuilder builder) {
		String cn = getClassName();
		Formatter formatter = new Formatter();
		formatter.format("new %s(\"%s\", %s, %s, %s, %d, %d, %s, %b, %s)", cn,
				name, makeFeaturesArray(builder, activeFeatures),
				makeFeaturesArray(builder, setupFeatures),
				makeRCHandlersArray(builder, rcHandlers),
				getKeyPressedInterestMask(rcHandlers),
				getKeyReleasedInterestMask(rcHandlers),
				makeCommandsArray(builder, onEntryCommands), nextOnSetupDone,
				makeCommandsArray(builder, nextCommands));
		return formatter.toString();
	}

	public int getKeyPressedInterestMask(SERCHandler[] rcHandlers) {
		int pressedMask = 0;
		for (int i = 0; i < rcHandlers.length; i++) {
			SERCHandler h = rcHandlers[i];
			pressedMask = pressedMask | h.getKeyPressedInterestMask(h);
		}
		return pressedMask;
	}

	public int getKeyReleasedInterestMask(SERCHandler[] rcHandlers) {
		int releasedMask = 0;
		for (int i = 0; i < rcHandlers.length; i++) {
			SERCHandler h = rcHandlers[i];
			releasedMask = releasedMask | h.getKeyReleasedInterestMask(h);
		}
		return releasedMask;
	}

	@Override
	protected String getClassName() {
		return "Segment";
	}

}
